﻿using Newtonsoft.Json;
using System;
using System.Linq;
using System.Web.Http;
using ZBJF.Warranty.BLL;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.Model;
using ZBJF.Warranty.DAL;
namespace ZBJF.Warranty.UdeskApi.Controllers
{
    public class MessageEventController : ApiController
    {
        private static readonly object obj = new object();
        [HttpPost]
        public void EventIndex()
        {
            string aaa = Request.Content.ReadAsStringAsync().Result;

            LogHelper.WriteLog("udsk消息事件内容" + aaa, LogType.remark);
            if (string.IsNullOrEmpty(aaa))
                return;
            MessageEventModel model = null;
            lock (obj)
            {
                try
                {
                    model = JsonConvert.DeserializeObject<MessageEventModel>(aaa);
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog("反序列化udsk消息事件内容异常：" + ex.ToString() + "；\r\n --------消息内容：" + aaa, LogType.error);
                    return;
                }
                switch (model.action)
                {
                    case "Customer_create":
                        AddUdeskCustomer(model.message);
                        break;
                    case "Customer_update":
                        EditUdeskCustomer(model.message);
                        break;
                    default:
                        break;
                }

            }
        }

        #region 新增客户信息
        private void AddUdeskCustomer(Message model)
        {
            if (model == null || model.id < 1)
                return;
            string phones = "", openid = "";
            if (model.cellphones != null)
            {
                foreach (var item in model.cellphones)
                {
                    if (!string.IsNullOrEmpty(item.content))
                        phones += item.content + "|";
                }
            }
            if (phones.Length > 1)
                phones = phones.TrimEnd('|');
            if (model.weixins != null && model.weixins.Count > 0)
                openid = model.weixins[0].openid;

            Udesk_CustomerInfo info = ServiceFactory.Udesk_CustomerInfoServiceInstance.LoadEntities(t => t.UdeskID == model.id).FirstOrDefault();
            if (info != null)
            {
                info.UdeskID = model.id;
                info.Description = string.IsNullOrEmpty(model.description) ? info.Description : model.description;
                info.Nick_name = string.IsNullOrEmpty(model.nick_name) ? info.Nick_name : model.nick_name;
                info.Email = string.IsNullOrEmpty(model.email) ? info.Email : model.email;
                info.Owner_id = model.owner_id.HasValue ? model.owner_id.Value : info.ID;
                info.Source_channel = string.IsNullOrEmpty(model.source_channel) ? info.Source_channel : model.source_channel;
                info.Cellphones =string.IsNullOrEmpty( phones)? info.Cellphones: phones;
                info.Openid = string.IsNullOrEmpty(openid) ? info.Openid : openid;
            }
            else
            {
                info = new Udesk_CustomerInfo()
                {
                    Description = model.description ?? "",
                    Nick_name = model.nick_name ?? "",
                    Email = model.email ?? "",
                    Owner_id = model.owner_id.HasValue ? model.owner_id.Value : 0,
                    UdeskID = model.id,
                    Source_channel = model.source_channel ?? "",
                    Cellphones = phones,
                    Openid = openid
                };

            }
            if (model.changes != null)
            {
                if (model.changes.email != null && model.changes.email.Length == 2)
                {
                    info.Email = model.changes.email[1];
                }
                if (model.changes.description != null && model.changes.description.Length == 2)
                {
                    info.Description = model.changes.description[1];
                }
                if (model.changes.nick_name != null && model.changes.nick_name.Length == 2)
                {
                    info.Nick_name = model.changes.nick_name[1];
                }
                if (model.changes.owner_id != null && model.changes.owner_id.Length == 2)
                {
                    info.Owner_id = model.changes.owner_id[1].HasValue ? model.changes.owner_id[1].Value : 0;
                }
                if (model.changes.cellphones != null && model.changes.cellphones.content != null && model.changes.cellphones.content.Length == 2)
                {
                    info.Cellphones = model.changes.cellphones.content[1];
                }
            }
            bool result = false;
            if (info.ID > 0)
            {
                result = ServiceFactory.Udesk_CustomerInfoServiceInstance.UpdateEntities(info);
            }
            else
            {
                info = ServiceFactory.Udesk_CustomerInfoServiceInstance.AddEntities(info);
                result = info.ID > 0;
            }

            if (!result)
                LogHelper.WriteLog("新增客户信息失败：" + JsonConvert.SerializeObject(model) + "；\r\n ------数据库实体对象：" + JsonConvert.SerializeObject(info), LogType.remark);
        }
        #endregion


        #region 修改客户信息
        private void EditUdeskCustomer(Message model)
        {
            if (model == null || model.id < 1)
                return;
            Udesk_CustomerInfo info = ServiceFactory.Udesk_CustomerInfoServiceInstance.LoadEntities(t => t.UdeskID == model.id).FirstOrDefault();
            //新增
            if (info == null)
            {
                AddUdeskCustomer(model);
                return;
            }
            //修改
            else
            {
                if (model.changes == null)
                    return;
                if (model.changes.email != null && model.changes.email.Length == 2)
                {
                    info.Email = model.changes.email[1];
                }
                if (model.changes.description != null && model.changes.description.Length == 2)
                {
                    info.Description = model.changes.description[1];
                }
                if (model.changes.nick_name != null && model.changes.nick_name.Length == 2)
                {
                    info.Nick_name = model.changes.nick_name[1];
                }
                if (model.changes.owner_id != null && model.changes.owner_id.Length == 2)
                {
                    info.Owner_id = model.changes.owner_id[1].HasValue ? model.changes.owner_id[1].Value : 0;
                }
                if (model.changes.cellphones != null && model.changes.cellphones.content != null && model.changes.cellphones.content.Length == 2)
                {
                    if (string.IsNullOrEmpty(model.changes.cellphones.content[0]))
                        info.Cellphones = info.Cellphones + "|" + model.changes.cellphones.content[1];
                    else
                        info.Cellphones = info.Cellphones.Replace(model.changes.cellphones.content[0], model.changes.cellphones.content[1]);
                }
                bool result = ServiceFactory.Udesk_CustomerInfoServiceInstance.UpdateEntities(info);
                if (!result)
                {

                    LogHelper.WriteLog("修改客户信息失败：" + JsonConvert.SerializeObject(model) + "；\r\n ------数据库实体对象：" + JsonConvert.SerializeObject(info), LogType.remark);
                }
            }
        }
        #endregion

    }
}